/**
 * @swagger
 * /api/high-goods/time-analysis:
 *   get:
 *     tags:
 *       - 高价值品统计
 *     summary: 获取高价值品时间分析数据
 *     description: 分析高价值品的时间分布、趋势和周期性规律
 *     responses:
 *       200:
 *         description: 成功获取时间分析数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "时间分析获取成功"
 *                   description: 响应消息
 *                 data:
                   type: object
                   properties:
                     yearlyAnalysis:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           year:
 *                             type: number
 *                             description: 年份
 *                           recordCount:
 *                             type: number
 *                             description: 记录数
 *                           unitCount:
 *                             type: number
 *                             description: 单位数
 *                           totalQuantity:
 *                             type: number
 *                             description: 总数量
 *                           totalAmount:
 *                             type: number
 *                             description: 总金额
 *                           avgQuantity:
 *                             type: string
 *                             description: 平均数量
 *                           avgAmount:
 *                             type: string
 *                             description: 平均金额
 *                     monthlyAnalysis:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           month:
 *                             type: string
 *                             description: 月份
 *                           recordCount:
 *                             type: number
 *                             description: 记录数
 *                           totalQuantity:
 *                             type: number
 *                             description: 总数量
 *                           totalAmount:
 *                             type: number
 *                             description: 总金额
 *                               type: string
 *                               description: 最晚时间
 *                             totalRecords:
 *                               type: integer
 *                               description: 总记录数
 *                             totalQuantity:
 *                               type: integer
 *                               description: 总数量
 *                             totalAmount:
 *                               type: number
 *                               description: 总金额
 *                     monthlyTrends:
 *                       type: object
 *                       properties:
 *                         description:
 *                           type: string
 *                           example: "月度趋势分析"
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               month:
 *                                 type: string
 *                                 description: 月份
 *                               recordCount:
 *                                 type: integer
 *                                 description: 记录数
 *                               totalQuantity:
 *                                 type: integer
 *                                 description: 总数量
 *                               totalAmount:
 *                                 type: number
 *                                 description: 总金额
 *                               avgQuantity:
 *                                 type: number
 *                                 description: 平均数量
 *                               avgAmount:
 *                                 type: number
 *                                 description: 平均金额
 *                     yearlyTrends:
 *                       type: object
 *                       properties:
 *                         description:
 *                           type: string
 *                           example: "年度趋势分析"
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               year:
 *                                 type: string
 *                                 description: 年份
 *                               recordCount:
 *                                 type: integer
 *                                 description: 记录数
 *                               totalQuantity:
 *                                 type: integer
 *                                 description: 总数量
 *                               totalAmount:
 *                                 type: number
 *                                 description: 总金额
 *       500:
 *         description: 服务器内部错误
 */
import { withCors } from '../../../lib/cors';
const { success, error: createError, handleResponse } = require('../../../lib/response');
const { query } = require('../../../lib/db');

/**
 * 处理高价值品时间分析请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {

  try {
    
    // 时间基础统计
    const timeBasicQuery = `
      SELECT 
        COUNT(DISTINCT TJSJ) as totalTimePoints,
        MIN(TJSJ) as earliestTime,
        MAX(TJSJ) as latestTime,
        COUNT(*) as totalRecords,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''
    `;

    const timeBasicResult = await query(timeBasicQuery);
    const timeBasic = timeBasicResult[0];

    // 年度统计
    const yearlyQuery = `
      SELECT 
        YEAR(TJSJ) as year,
        COUNT(*) as recordCount,
        COUNT(DISTINCT DWMC) as unitCount,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount,
        AVG(COALESCE(GJZSL, 0)) as avgQuantity,
        AVG(COALESCE(GJZJE, 0)) as avgAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''
      GROUP BY YEAR(TJSJ)
      ORDER BY year DESC
    `;

    const yearlyResult = await query(yearlyQuery);

    // 月度统计
    const monthlyQuery = `
      SELECT 
        DATE_FORMAT(TJSJ, '%Y-%m') as month,
        COUNT(*) as recordCount,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''
      GROUP BY DATE_FORMAT(TJSJ, '%Y-%m')
      ORDER BY month DESC
      LIMIT 12
    `;

    const monthlyResult = await query(monthlyQuery);

    const responseData = {
      yearlyAnalysis: yearlyResult.map(item => ({
        year: parseInt(item.year),
        recordCount: parseInt(item.recordCount),
        unitCount: parseInt(item.unitCount),
        totalQuantity: parseInt(item.totalQuantity),
        totalAmount: parseFloat(item.totalAmount),
        avgQuantity: parseFloat(item.avgQuantity).toFixed(2),
        avgAmount: parseFloat(item.avgAmount).toFixed(2)
      })),
      monthlyAnalysis: monthlyResult.map(item => ({
        month: item.month,
        recordCount: parseInt(item.recordCount),
        totalQuantity: parseInt(item.totalQuantity),
        totalAmount: parseFloat(item.totalAmount)
      }))
    };

    return handleResponse(res, success(responseData, "时间分析获取成功"));
    
  } catch (err) {
    console.error('High goods time analysis error:', err);
    return handleResponse(res, createError("获取时间分析失败", 500));
  }
}

export default withCors(handler, ['GET']);